package md.NJavaOppo;
import android.app.Activity;
import android.content.pm.ApplicationInfo;
import android.content.pm.PackageManager;
import android.util.Log;

import com.heytap.msp.mobad.api.ad.RewardVideoAd;
import com.heytap.msp.mobad.api.listener.IRewardVideoAdListener;
import com.heytap.msp.mobad.api.params.RewardVideoAdParams;

import java.util.Timer;
import java.util.TimerTask;

import md.NJavaBase.AdType;
import md.NJavaBase.IAd;
import md.NJavaBase.IAdCallback;
import md.NJavaBase.ICallbackLight;
import md.NJavaBase.NJavaBase;

public class OppoVideoAd implements IAd, IRewardVideoAdListener {
    static String Tag = "OppoVideoAd";

    public AdType getAdType(){
        return AdType.rewardVideo;
    }

    public  OppoVideoAd(int priority)
    {
        m_Priority = priority;
        m_NeedRecallClose = false;


        Activity activity = NJavaBase.getActivity();

        String REWARD_VIDEO_POS_ID = "";
        try {
            ApplicationInfo appInfo = activity.getPackageManager().getApplicationInfo(
                    activity.getPackageName(), PackageManager.GET_META_DATA
            );

            REWARD_VIDEO_POS_ID = appInfo.metaData.getString("OPPO_REWARD_VIDEO_POS_ID")  ;
            if(REWARD_VIDEO_POS_ID.length()>2&&REWARD_VIDEO_POS_ID.charAt(0)=='I'&&REWARD_VIDEO_POS_ID.charAt(1)=='D') REWARD_VIDEO_POS_ID = REWARD_VIDEO_POS_ID.substring(2);
        } catch (PackageManager.NameNotFoundException e) {
            NJavaBase.logOut(Tag, "OppoVideoAd error!");
            e.printStackTrace();
        }

        NJavaBase.logOut(Tag, "begin new video obj");
        mRewardVideoAd = new RewardVideoAd(activity, REWARD_VIDEO_POS_ID, this);
        NJavaBase.logOut(Tag, "end new video obj");
    }

    //是否已经初始化完毕，可以开始加载视频
    public boolean isInitialized()  { return  OppoAd.isInited();  }

    //广告平台的名称
    public String adName(){  return "Oppo";  }


    //是否需要由loader去检查加载超时
    public boolean needCheckLoadOvertime(){return false;}


    //优先级，值越大越优先
    public int getPriority() { return m_Priority; }


    //是否已经过期
    public boolean isInvalidated() {  return !mRewardVideoAd.isReady(); }

    //预装 回调0表示预装成功 99表示预装失败  2可以获得奖励（仅视频广告需要） 3已关闭
    public void reloadAd(IAdCallback callBack)
    {
        mCallback = callBack;

         /**
         * 调用loadAd方法请求激励视频广告;通过RewardVideoAdParams.setFetchTimeout方法可以设置请求
         * 视频广告最大超时时间，单位毫秒；
         */
        RewardVideoAdParams rewardVideoAdParams = new RewardVideoAdParams.Builder()
                .setFetchTimeout(10000)
                .build();
        mRewardVideoAd.loadAd(rewardVideoAdParams);
        NJavaBase.logOut(Tag, "请求加载视频广告!");

    }

    //显示视频
    public void show()
    {
        if (mRewardVideoAd.isReady()) {
            m_NeedRecallClose = true;
            mRewardVideoAd.showAd();
        }
    }



    @Override
    public void onAdSuccess() {
        mCallback.onLoad();//reCall( new Integer(0));
        NJavaBase.logOut(Tag, "视频广告缓存成功!");
    }


    @Override
    public void onAdFailed(int code, String msg) {
        /**
         * 请求广告失败、不展示播放视频的入口Dialog
         */
        mCallback.onError(msg);//( new Integer(99));
        NJavaBase.logOut(Tag, "请求视频广告失败. msg=" + msg);
    }

    @Override
    public void onAdFailed(String msg)
    {
        mCallback.onError(msg);//reCall( new Integer(99));
        NJavaBase.logOut(Tag, "请求视频广告失败#1. msg=" + msg);
    }

    @Override
    public void onAdClick(long currentPosition) {
        //printStatusMsg("视频广告被点击，当前播放进度 = " + currentPosition + " 秒");
    }

    @Override
    public void onVideoPlayStart() {
        //printStatusMsg("视频开始播放.");
    }

    @Override
    public void onVideoPlayComplete() {
        /**
         * TODO 注意：从SDK 3.0.1版本开始，不能在激励视频广告播放完成回调-onVideoPlayComplete里做任何激励操作，统一在onReward回调里给予用户激励。
         */
        NJavaBase.logOut(Tag, "视频广告播放完成.");

        //回调视频播放完成,通知可以获得奖励
        mCallback.onReward();//reCall( new Integer(2));

        //通知视频关闭
        if(m_NeedRecallClose)
        {
            Timer reloadTimer = new Timer();// 实例化Timer类
            class overTimeTask extends TimerTask {
                public void run() {
                    class reloadRunnable implements Runnable {
                        @Override
                        public void run() {
                            if(m_NeedRecallClose) {
                                m_NeedRecallClose = false;
                                mCallback.onClose();//reCall( new Integer(3));
                            }
                        }
                    }
                    NJavaBase.getActivity().runOnUiThread(new reloadRunnable());
                    this.cancel();
                }
            }
            reloadTimer.schedule(new overTimeTask(), 300);// 毫秒
        }
    }

    @Override
    public void onVideoPlayError(String msg) {
        mCallback.onError(msg);//reCall(99);
        NJavaBase.logOut(Tag, "视频播放错误，错误信息=" + msg);
    }

    @Override
    public void onVideoPlayClose(long currentPosition) {
        NJavaBase.logOut(Tag,"视频广告被关闭，当前播放进度 = " + currentPosition + " 秒");
        if(m_NeedRecallClose) {
            m_NeedRecallClose = false;
            mCallback.onClose();//reCall( new Integer(3));
        }
    }

    @Override
    public void onLandingPageOpen() {
        Log.d(Tag, "视频广告落地页打开." );
    }

    @Override
    public void onLandingPageClose() {
        Log.d(Tag, "视频广告落地页关闭." );
    }

    /**
     * add 2018-10-25
     *
     * @param objects
     */
    @Override
    public void onReward(Object... objects) {
        NJavaBase.logOut(Tag, "奖励.=====" );
        /**
         * TODO 注意：只能在收到onReward回调的时候才能给予用户奖励。
         */
        /*
        printStatusMsg("给用户发放奖励.");
        AlertDialog alertDialog = new AlertDialog.Builder(this)
                .setCancelable(false)
                .setTitle("获取奖励提示")
                .setMessage(REWARD_TOAST_TEXT)
                .setPositiveButton("确定", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        dialog.dismiss();
                    }
                })
                .create();
        alertDialog.show();
        */
    }


    int m_Priority;
    RewardVideoAd mRewardVideoAd;
    IAdCallback mCallback;
    boolean m_NeedRecallClose;
}
